<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <input type="file" @change="fileChange" />
    <!-- <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" /> -->
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import axios from 'axios'
// import HelloWorld from '@/components/HelloWorld.vue' // @ is an alias to /src

export default defineComponent({
  name: 'Home',
  components: {
    // HelloWorld
  },
  created() {
    // this.getData()
  },
  methods: {
    /**
     * 1. 拿到图片描述信息
     * 2. 封装base64方法，将图片转成base64格式
     * 3. 将base64格式传递给后台接口
     *
     * 4. 通过post请求，拿到参数base64格式的图片；
     * 5. 使用百度第三方服务ocr接口，将当前的base64转成文字，返回给前端
     */
    async fileChange(file) {
      // file图片描述信息

      // console.log('fi;e:', file.target.files)
      const fileBase = await this.getBase64(file.target.files[0])
      const res = await this.getData(fileBase)
      console.log('res:', res)
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        var fr = new FileReader()
        fr.onloadend = function (e) {
          // console.log(
          //   'e.target.result:',
          //   e.target.result.replace('data:image/png;base64,', '')
          // )
          const base64 = e.target.result.replace('data:image/png;base64,', '')
          resolve(base64)
        }
        fr.readAsDataURL(file)
      })
    },
    async getData(fileBase) {
      // const data = await axios.get('/api/test')
      const data = await axios.post(
        '/api/ocr/text',
        { file: fileBase },
        {
          headers: {
            Authorization:
              'Bearer ' +
              'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImRlcHRJZCI6WyI2MTIwNDc5NzgxMDIwYWZiMWEzYjczYmEiXSwic3RhdGUiOjIsInJvbGUiOjAsInJvbGVMaXN0IjpudWxsLCJfaWQiOiI2MTFmNmNkMzUyYTJlM2YwZjgxZWRjN2QiLCJ1c2VyTmFtZSI6ImFkbWluIiwidXNlckVtYWlsIjoiYWRtaW5AMTYzLmNvbSJ9LCJpYXQiOjE2MzAwMjkwODgsImV4cCI6MTYzMDExNTQ4OH0.ZJY7cIg5WUb8ZxZtIhyTEqMyOWsBfi2kB7WjTfK7nvc'
          }
        }
      )
      console.log('data:', data)
      return data
    }
  }
})
</script>
